package com.dusk.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dusk.pojo.House;
import com.dusk.pojo.Message;
import com.dusk.pojo.User;
import com.dusk.service.HouseService;
import com.dusk.service.MessageService;
import com.dusk.utils.Contants;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 房屋信息控制层
 */
@RestController
public class HouseController {

    @Resource
    private HouseService houseService;

    @Resource
    private MessageService messageService;

    /**
     * 获取房屋租用数据
     *
     * @return 返回租用房屋信息数据json
     */
    @GetMapping("/house/houseRent")
    public String houseRent() throws IOException {
        //1.先获取数据库的所有数据
        List<House> houses = houseService.queryAllHouseRent();
        //2.转换成json数据返回给前端
        String data = JSON.toJSONString(houses);
        //System.out.println(data);
        return data;
    }

    //分页,出租
    @PostMapping(value = "/house/houseRent/p={page}", produces = "application/json;charset=UTF-8")
    public String housePage(@PathVariable("page") Integer current_page, @RequestBody String params) throws IOException {
        int pageSize;
        int page;
        if (current_page == null) {
            page = 1;
        } else {
            page = current_page;
        }
        if (params == null) {
            pageSize = 10;
        } else {
            String data = JSON.parseObject(params, String.class);

            pageSize = Integer.parseInt(data);
        }
        //设置分页参数
        //System.out.println("获取的数据，起始页："+page+"，每个的个数："+pageSize);
        PageHelper.startPage(page, pageSize);
        //获取数据库的所有数据
        List<House> houses = houseService.queryAllHouseRent();
        //其他分页的数据
        PageInfo<House> pageInfo = new PageInfo<>(houses);
        //System.out.println("总条数："+pageInfo.getTotal());
        //System.out.println("总页数："+pageInfo.getPages());
        //System.out.println("当前页："+pageInfo.getPageNum());
        //System.out.println("每页显示长度："+pageInfo.getPageSize());
        //System.out.println("是否第一页："+pageInfo.isIsFirstPage());
        //System.out.println("是否最后一页："+pageInfo.isIsLastPage());
        //2.转换成json数据返回给前端
        String data = JSON.toJSONStringWithDateFormat(pageInfo, "yyyy-MM-dd HH:mm:ss");
        //System.out.println(data);
        return data;
    }

    //分页，出售
    @PostMapping(value = "/house/houseBuy/p={page}", produces = "application/json;charset=UTF-8")
    public String housePageBuy(@PathVariable("page") Integer current_page, @RequestBody String params) throws IOException {
        int pageSize;
        int page;
        if (current_page == null) {
            page = 1;
        } else {
            page = current_page;
        }
        if (params == null) {
            pageSize = 10;
        } else {
            String data = JSON.parseObject(params, String.class);

            pageSize = Integer.parseInt(data);
        }
        //设置分页参数
        //System.out.println("获取的数据，起始页："+page+"，每个的个数："+pageSize);
        PageHelper.startPage(page, pageSize);
        //获取数据库的所有数据
        List<House> houses = houseService.queryAllHouseBuy();
        //其他分页的数据
        PageInfo<House> pageInfo = new PageInfo<>(houses);
        //System.out.println("总条数："+pageInfo.getTotal());
        //System.out.println("总页数："+pageInfo.getPages());
        //System.out.println("当前页："+pageInfo.getPageNum());
        //System.out.println("每页显示长度："+pageInfo.getPageSize());
        //System.out.println("是否第一页："+pageInfo.isIsFirstPage());
        //System.out.println("是否最后一页："+pageInfo.isIsLastPage());
        //2.转换成json数据返回给前端
        String data = JSON.toJSONStringWithDateFormat(pageInfo, "yyyy-MM-dd HH:mm:ss");
        //System.out.println(data);
        return data;
    }


    //房屋详细界面
    @GetMapping("/all-order-manage-edit/{id}")
    public String getOrderEdit(@PathVariable("id") Integer id) {
        House house = houseService.queryHouseById(id);
        return JSON.toJSONStringWithDateFormat(house, "yyyy-MM-dd HH:mm:ss");
    }

    //获取留言信息
    @GetMapping("/all-order-manage-edit/uuid/message")
    public String getOrderEditMessage(@RequestParam String uuid) {
        //System.out.println("走这个路径留言信息");
        List<Message> messages = messageService.queryMessageByUuid(uuid);

        //System.out.println("获取后台数据："+messages);
        return JSON.toJSONStringWithDateFormat(messages, "yyyy-MM-dd HH:mm:ss");
    }

    //获取留言信息
    @PostMapping(value = "/all-order-manage-edit/message/add", produces = "application/json;charset=UTF-8")
    public String addMessage(@RequestBody String params) {
        Message message = JSON.parseObject(params, Message.class);
        messageService.addMessage(message);
        String data = JSON.toJSONString("ok");
        return data;
    }


    //获取更新分数
    @GetMapping("/all-order-manage-edit/score/update")
    public String updateScore(@RequestParam("id") Integer id, @RequestParam("score") Integer score) {
        House one = houseService.queryHouseById(id);
        double scoreNow = one.getScore();
        double res = (score + scoreNow) / 2;
        //System.out.println("测试"+res);
        houseService.updateScore(id, res);  //更新分数
        //System.out.println("后台更新评分成功！");
        String data = JSON.toJSONString("ok");
        return data;
    }


    //用户增加房屋信息
    @PostMapping(value = "/all-order-create-house/house/insert", produces = "application/json;charset=UTF-8")
    public String addHouse(@RequestBody String params) {
        House house = JSON.parseObject(params, House.class);
        int msg = houseService.insertHouse(house);
        System.out.println("房屋增加：" + msg);  //若输出1: 表示增加成功
        String data = JSON.toJSONString("ok");
        return data;
    }


    //根据条件查询相关房屋信息
    @PostMapping(value = "/parse/house/query", produces = "application/json;charset=UTF-8")
    public String parseHouse(@RequestBody String params,
                             @RequestParam(value = "user", required = false) String isUser,
                             HttpServletRequest request)
    {
        System.out.println("进入测试房屋信息查询：");
        JSONObject outJson = JSONObject.parseObject(params);

        String price = outJson.getString("price");
        Date date1 = outJson.getDate("date1");
        Date date2 = outJson.getDate("date2");
        String type = outJson.getString("type");
        Double score1 = outJson.getDouble("score1");
        Double score2 = outJson.getDouble("score2");
        Integer status = outJson.getInteger("status");

        if (isUser != null) {
            User user = (User) request.getSession().getAttribute(Contants.USER_SESSION);

            if (isUser.equals("rent")) {
                status = 1;
            } else if (isUser.equals("buy")) {
                status = 2;
            }
        }


        List<House> houses = houseService.queryHouseByCondition(
                price, date1, date2, type, score1,
                score2, status);
        System.out.println("条件查询结果:");
        for (House house : houses) {
            System.out.println(house);
        }
        String data = JSON.toJSONString(houses);
        return data;
    }

    //个人用户查询出租信息
    @PostMapping(value = "/house/user/p={page}", produces = "application/json;charset=UTF-8")
    public String queryUserRentHouse(@PathVariable("page") Integer current_page,
                                     @RequestBody String params, HttpServletRequest request) throws IOException {
        User user = (User) request.getSession().getAttribute(Contants.USER_SESSION);
        int pageSize;
        int page;
        if (current_page == null) {
            page = 1;
        } else {
            page = current_page;
        }
        if (params == null) {
            pageSize = 10;
        } else {
            String data = JSON.parseObject(params, String.class);
            pageSize = Integer.parseInt(data);
        }
        PageHelper.startPage(page, pageSize);
        //获取数据库的所有数据
        List<House> houses = houseService.queryHouseByUuidAndStatus(user.getUserUuid(), 1);
        for (House house : houses) {
            System.out.println(house);
        }
        //其他分页的数据
        PageInfo<House> pageInfo = new PageInfo<>(houses);
        //2.转换成json数据返回给前端
        String data = JSON.toJSONStringWithDateFormat(pageInfo, "yyyy-MM-dd HH:mm:ss");
        return data;
    }


    //更新用户房屋信息
    @PostMapping(value = "/house/user/update", produces = "application/json;charset=UTF-8")
    public String updateHouse(@RequestBody String params) {
        House house = JSON.parseObject(params, House.class);
        System.out.println("更新房屋信息测试：");
        System.out.println(house);
        int msg = houseService.updateHouse(house);
        System.out.println("房屋更改：" + msg);
        String data = JSON.toJSONString("ok");
        return data;
    }



    //根据id删除房屋信息
    @GetMapping("/user/delete/{id}")
    public void deleteHouseById(@PathVariable("id") int id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        int result = houseService.deleteHouseById(id);
        if (result >= 1) {
            System.out.println("删除成功！");
        } else {
            System.out.println("删除失败！");
        }
        //重新加载
        response.sendRedirect("/pages/user-rent.html");
    }


    //个人用户查询出租信息
    @PostMapping(value = "/house/userBuy/p={page}", produces = "application/json;charset=UTF-8")
    public String queryUserBuyHouse(@PathVariable("page") Integer current_page,
                                    @RequestBody String params, HttpServletRequest request) throws IOException {

        User user = (User) request.getSession().getAttribute(Contants.USER_SESSION);
        int pageSize;
        int page;
        if (current_page == null) {
            page = 1;
        } else {
            page = current_page;
        }
        if (params == null) {
            pageSize = 10;
        } else {
            String data = JSON.parseObject(params, String.class);
            pageSize = Integer.parseInt(data);
        }
        PageHelper.startPage(page, pageSize);
        //获取数据库的所有数据
        List<House> houses = houseService.queryHouseByUuidAndStatus(user.getUserUuid(), 2);
        for (House house : houses) {
            System.out.println(house);
        }
        //其他分页的数据
        PageInfo<House> pageInfo = new PageInfo<>(houses);
        //2.转换成json数据返回给前端
        String data = JSON.toJSONStringWithDateFormat(pageInfo, "yyyy-MM-dd HH:mm:ss");
        return data;
    }


    /**
     * 图片上传
     *
     * @param photo
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadPhoto", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> uploadPhoto(MultipartFile photo, HttpServletRequest request) {
        Map<String, String> ret = new HashMap<String, String>();
        if (photo == null) {
            ret.put("type", "error");
            ret.put("msg", "选择要上传的文件！");
            return ret;
        }
        if (photo.getSize() > 1024 * 1024 * 10) {
            ret.put("type", "error");
            ret.put("msg", "文件大小不能超过10M！");
            return ret;
        }
        //获取文件后缀
        String suffix = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf(".") + 1, photo.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            ret.put("type", "error");
            ret.put("msg", "请选择jpg,jpeg,gif,png格式的图片！");
            return ret;
        }
        //获取项目根目录加上图片目录
        String savePath = request.getSession().getServletContext().getRealPath("/") + "/imagesUpload/";
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        //名字由时间加uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String filename = new Date().getTime() + "_" + uuid + "." + suffix;
        try {
            //将文件保存指定目录
            photo.transferTo(new File(savePath + filename));
        } catch (Exception e) {
            ret.put("type", "error");
            ret.put("msg", "保存文件异常！");
            e.printStackTrace();
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "上传图片成功！");
        ret.put("filepath", request.getSession().getServletContext().getContextPath() + "/imagesUpload/");
        ret.put("filename", filename);
        System.out.println("图片上传测试成功");
        return ret;
    }
}

